<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getCurrentUser } from '../services/auth';
import { uploadVideo, getVideoCategories, getVideoById, updateVideo } from '../services/video';

const router = useRouter();
const route = useRoute();
const currentUser = ref(getCurrentUser());
const isEditing = ref(false);

// 视频上传表单数据
const formData = reactive({
  title: '',
  description: '',
  category: '',
  tags: '',
  releaseDate: new Date().toISOString().split('T')[0],
  duration: '',
  director: '',
  actors: '',
  cover: '',
  videoUrl: ''
});

// 状态管理
const isSubmitting = ref(false);
const errors = ref({});
const successMessage = ref('');
const videoCategories = ref(getVideoCategories());
const selectedFiles = ref({
  cover: null,
  video: null
});
const previewUrls = ref({
  cover: '',
  video: ''
});

// 验证表单
const validateForm = () => {
  errors.value = {};
  let isValid = true;
  
  // 标题验证
  if (!formData.title.trim()) {
    errors.value.title = '请输入视频标题';
    isValid = false;
  } else if (formData.title.length > 100) {
    errors.value.title = '标题长度不能超过100个字符';
    isValid = false;
  }
  
  // 描述验证
  if (!formData.description.trim()) {
    errors.value.description = '请输入视频描述';
    isValid = false;
  }
  
  // 分类验证
  if (!formData.category) {
    errors.value.category = '请选择视频分类';
    isValid = false;
  }
  
  // 标签验证
  if (!formData.tags.trim()) {
    errors.value.tags = '请输入视频标签';
    isValid = false;
  }
  
  // 视频文件验证（编辑模式下可以保留原视频）
  if (!isEditing.value && !previewUrls.value.video && !formData.videoUrl) {
    errors.value.video = '请上传视频文件或输入视频URL';
    isValid = false;
  }
  
  return isValid;
};

// 初始化
const init = async () => {
  const user = await getCurrentUser();
  if (!user) {
    router.push('/login');
  } else {
    currentUser.value = user;
    // 如果是编辑模式，加载视频数据
    await loadVideoDataForEdit();
  }
};

// 处理封面图片选择
const handleCoverChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFiles.value.cover = file;
    // 创建预览URL
    previewUrls.value.cover = URL.createObjectURL(file);
    // 清除错误
    if (errors.value.cover) {
      delete errors.value.cover;
    }
  }
};

// 模拟上传文件并生成URL
const simulateUpload = (file, type) => {
  return new Promise((resolve) => {
    // 模拟网络延迟
    setTimeout(() => {
      // 在实际应用中，这里应该调用后端API上传文件
      // 这里仅生成一个模拟的URL
      const timestamp = Date.now();
      const url = type === 'video' ? 
        `https://example.com/videos/${timestamp}.mp4` : 
        `https://example.com/thumbnails/${timestamp}.jpg`;
      resolve(url);
    }, 500);
  });
};

// 加载编辑视频数据
const loadVideoDataForEdit = async () => {
  const videoId = route.query.edit;
  if (videoId) {
    try {
      const video = await getVideoById(videoId);
      if (video && video.userId === currentUser.value?.id) {
        isEditing.value = true;
        formData.id = video.id;
        formData.title = video.title;
        formData.description = video.description;
        formData.tags = video.tags.join(', ');
        formData.category = video.category;
        formData.cover = video.cover || '';
        formData.videoUrl = video.videoUrl;
        previewUrls.value.cover = video.cover || '';
      } else {
        alert('无权编辑此视频');
        router.push('/upload-video');
      }
    } catch (error) {
      console.error('加载视频数据失败:', error);
      alert('加载视频数据失败');
    }
  }
};

// 处理视频文件选择
const handleVideoChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFiles.value.video = file;
    // 创建预览URL
    previewUrls.value.video = URL.createObjectURL(file);
    // 清除错误
    if (errors.value.video) {
      delete errors.value.video;
    }
  }
};

// 处理上传/更新
const handleSubmit = async () => {
  // 重置消息
  successMessage.value = '';
  
  // 验证表单
  if (!validateForm()) {
    return;
  }
  
  isSubmitting.value = true;
  
  try {
    // 处理文件上传（只有在提供了新文件时才上传）
    let newVideoUrl = formData.videoUrl;
    let newCoverUrl = formData.cover;
    
    if (selectedFiles.value.video) {
      newVideoUrl = await simulateUpload(selectedFiles.value.video, 'video');
    }
    
    if (selectedFiles.value.cover) {
      newCoverUrl = await simulateUpload(selectedFiles.value.cover, 'image');
    }
    
    // 准备提交数据
    const submissionData = {
      ...formData,
      tags: formData.tags.split(',').map(tag => tag.trim()).filter(tag => tag),
      actors: formData.actors ? formData.actors.split(',').map(actor => actor.trim()).filter(actor => actor) : [],
      cover: newCoverUrl,
      videoUrl: newVideoUrl
    };
    
    let result;
    if (isEditing.value) {
      // 更新视频
      result = await updateVideo(submissionData.id, submissionData);
      if (result.success) {
        successMessage.value = '视频更新成功！';
        
        // 3秒后跳转到视频详情页
        setTimeout(() => {
          router.push(`/video/${submissionData.id}`);
        }, 3000);
      } else {
        errors.value.general = result.error || '更新失败，请稍后重试';
      }
    } else {
      // 调用上传服务
      result = await uploadVideo(submissionData, currentUser.value.id, currentUser.value.username);
      
      if (result.success) {
        successMessage.value = '视频上传成功！';
        
        // 3秒后跳转到视频详情页
        setTimeout(() => {
          router.push(`/video/${result.video.id}`);
        }, 3000);
      } else {
        errors.value.general = result.error || '上传失败，请稍后重试';
      }
    }
  } catch (error) {
    console.error(isEditing.value ? 'Update error:' : 'Upload error:', error);
    errors.value.general = '过程中发生错误，请稍后重试';
  } finally {
    isSubmitting.value = false;
  }
};

// 返回按钮
const goBack = () => {
  router.back();
};

// 组件挂载时初始化
onMounted(() => {
  init();
});
</script>

<template>
  <div class="upload-video-container">
    <div class="upload-video-header">
      <h1>{{ isEditing ? '编辑视频' : '上传视频' }}</h1>
      <button class="back-button" @click="goBack">返回</button>
    </div>
    
    <div class="upload-video-form">
      <!-- 成功消息 -->
      <div v-if="successMessage" class="success-message">
        {{ successMessage }}
      </div>
      
      <!-- 错误消息 -->
      <div v-if="errors.general" class="error-message general-error">
        {{ errors.general }}
      </div>
      
      <form @submit.prevent="handleSubmit">
        <!-- 视频信息表单 -->
        <div class="form-section">
          <h2>视频基本信息</h2>
          
          <div class="form-group">
            <label for="title">视频标题 <span class="required">*</span></label>
            <input
              id="title"
              v-model="formData.title"
              type="text"
              placeholder="请输入视频标题（最多100个字符）"
              maxlength="100"
              :disabled="isSubmitting"
            />
            <div v-if="errors.title" class="error-text">{{ errors.title }}</div>
          </div>
          
          <div class="form-group">
            <label for="description">视频描述 <span class="required">*</span></label>
            <textarea
              id="description"
              v-model="formData.description"
              rows="5"
              placeholder="请详细描述您的视频内容"
              :disabled="isSubmitting"
            ></textarea>
            <div v-if="errors.description" class="error-text">{{ errors.description }}</div>
          </div>
          
          <div class="form-group">
            <label for="category">视频分类 <span class="required">*</span></label>
            <select
              id="category"
              v-model="formData.category"
              :disabled="isSubmitting"
            >
              <option value="" disabled>请选择分类</option>
              <option v-for="category in videoCategories" :key="category.value" :value="category.value">
                {{ category.label }}
              </option>
            </select>
            <div v-if="errors.category" class="error-text">{{ errors.category }}</div>
          </div>
          
          <div class="form-group">
            <label for="tags">视频标签 <span class="required">*</span></label>
            <input
              id="tags"
              v-model="formData.tags"
              type="text"
              placeholder="请输入标签，用逗号分隔（例如：动作,冒险,科幻）"
              :disabled="isSubmitting"
            />
            <div v-if="errors.tags" class="error-text">{{ errors.tags }}</div>
          </div>
        </div>
        
        <!-- 视频元数据表单 -->
        <div class="form-section">
          <h2>视频元数据</h2>
          
          <div class="form-row">
            <div class="form-group half">
              <label for="releaseDate">发布日期</label>
              <input
                id="releaseDate"
                v-model="formData.releaseDate"
                type="date"
                :disabled="isSubmitting"
              />
            </div>
            
            <div class="form-group half">
              <label for="duration">视频时长</label>
              <input
                id="duration"
                v-model="formData.duration"
                type="text"
                placeholder="例如：120分钟"
                :disabled="isSubmitting"
              />
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group half">
              <label for="director">导演</label>
              <input
                id="director"
                v-model="formData.director"
                type="text"
                placeholder="请输入导演姓名"
                :disabled="isSubmitting"
              />
            </div>
            
            <div class="form-group half">
              <label for="actors">演员</label>
              <input
                id="actors"
                v-model="formData.actors"
                type="text"
                placeholder="请输入演员姓名，用逗号分隔"
                :disabled="isSubmitting"
              />
            </div>
          </div>
        </div>
        
        <!-- 文件上传部分 -->
        <div class="form-section">
          <h2>文件上传</h2>
          
          <!-- 封面上传 -->
          <div class="form-group">
            <label for="coverUpload">视频封面</label>
            <div class="file-upload">
              <input
                id="coverUpload"
                type="file"
                accept="image/*"
                @change="handleCoverChange"
                :disabled="isSubmitting"
              />
              <label for="coverUpload" class="upload-button">选择图片</label>
              <span v-if="selectedFiles.cover" class="file-name">{{ selectedFiles.cover.name }}</span>
            </div>
            <div v-if="previewUrls.cover" class="preview-container">
              <img :src="previewUrls.cover" alt="封面预览" class="preview-image" />
            </div>
          </div>
          
          <!-- 视频上传 -->
          <div class="form-group">
            <label for="videoUpload">视频文件 <span class="required">*</span></label>
            <div class="file-upload">
              <input
                id="videoUpload"
                type="file"
                accept="video/*"
                @change="handleVideoChange"
                :disabled="isSubmitting"
              />
              <label for="videoUpload" class="upload-button">选择视频</label>
              <span v-if="selectedFiles.video" class="file-name">{{ selectedFiles.video.name }}</span>
            </div>
            <div v-if="errors.video" class="error-text">{{ errors.video }}</div>
            
            <!-- 视频预览 -->
            <div v-if="previewUrls.video" class="preview-container">
              <video :src="previewUrls.video" controls class="preview-video"></video>
            </div>
            
            <!-- 或输入视频URL（仅用于演示） -->
            <div class="or-divider">或</div>
            <input
              v-model="formData.videoUrl"
              type="text"
              placeholder="输入视频URL（仅用于演示）"
              :disabled="isSubmitting"
            />
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="button" class="cancel-button" @click="goBack" :disabled="isSubmitting">
            取消
          </button>
          <button type="submit" class="submit-button" :disabled="isSubmitting">
            {{ isSubmitting ? (isEditing ? '更新中...' : '上传中...') : (isEditing ? '更新视频' : '发布视频') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped>
.upload-video-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.upload-video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color);
}

.upload-video-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
}

.back-button {
  background-color: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-primary);
  padding: 10px 20px;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: var(--hover-background);
}

.upload-video-form {
  background-color: var(--white);
  border-radius: var(--border-radius);
  padding: 30px;
  box-shadow: var(--shadow-md);
}

.form-section {
  margin-bottom: 40px;
}

.form-section h2 {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-color);
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group.half {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.required {
  color: #ff4757;
}

.form-group input[type="text"],
.form-group input[type="date"],
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.form-group textarea {
  resize: vertical;
  min-height: 120px;
}

/* 文件上传样式 */
.file-upload {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.file-upload input[type="file"] {
  display: none;
}

.upload-button {
  background-color: var(--primary-color);
  color: white;
  padding: 10px 20px;
  border-radius: var(--border-radius);
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.upload-button:hover {
  background-color: var(--primary-dark);
}

.file-name {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 预览样式 */
.preview-container {
  margin-top: 15px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  overflow: hidden;
}

.preview-image {
  max-width: 100%;
  height: auto;
  display: block;
}

.preview-video {
  max-width: 100%;
  height: auto;
  display: block;
}

.or-divider {
  text-align: center;
  margin: 15px 0;
  color: var(--text-secondary);
  position: relative;
}

.or-divider::before,
.or-divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 40%;
  height: 1px;
  background-color: var(--border-color);
}

.or-divider::before {
  left: 0;
}

.or-divider::after {
  right: 0;
}

/* 错误和成功消息 */
.error-message,
.success-message {
  padding: 15px;
  border-radius: var(--border-radius);
  margin-bottom: 20px;
  font-size: 14px;
}

.error-message {
  background-color: #fee;
  color: #c33;
}

.success-message {
  background-color: #efe;
  color: #3c3;
}

.error-text {
  color: #c33;
  font-size: 12px;
  margin-top: 5px;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.cancel-button,
.submit-button {
  padding: 12px 30px;
  border-radius: var(--border-radius);
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-button {
  background-color: transparent;
  border: 1px solid var(--border-color);
  color: var(--text-primary);
}

.cancel-button:hover {
  background-color: var(--hover-background);
}

.submit-button {
  background-color: var(--primary-color);
  color: white;
  border: none;
}

.submit-button:hover {
  background-color: var(--primary-dark);
}

.submit-button:disabled,
.cancel-button:disabled,
.back-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 20px;
  }
  
  .form-group.half {
    margin-bottom: 20px;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .cancel-button,
  .submit-button {
    width: 100%;
  }
}
</style>